﻿using QueryZJK.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace QueryZJK.Helpers
{
    class SqlServerHelper : IDao
    {
        protected SqlServerHelper()
        {
        }

        static SqlServerHelper instance = null;
        public static SqlServerHelper Instance
        {
            get
            {
                return instance ?? (instance = new SqlServerHelper());
            }
        }

        public DataTable Select(string sql)
        {
            SqlConnection conn = GetConnection();

            SqlCommand cmd = new SqlCommand(sql, conn);

            DataTable data = new DataTable();

            try
            {
                SelectImplement(conn, sql, data);
            }
            catch (Exception ee)
            {
                throw new InvalidExpressionException(ee.Message + ":" + sql, ee);
            }
            finally
            {
                conn.Close(); //关闭连接
            }

            return data;
        }

        void SelectImplement(SqlConnection conn, string sql, DataTable data)
        {
            conn.Open();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = sql;

            var reader = cmd.ExecuteReader();
            var fieldCount = reader.FieldCount;

            //添加每列的列头
            for (int i = 0; i < fieldCount; i++)
            {
                DataColumn column = new DataColumn(reader.GetName(i));
                data.Columns.Add(column);
            }

            //每次循环就是一条记录
            while (reader.Read())
            {
                DataRow row = data.NewRow();
                for (int i = 0; i < fieldCount; i++)
                {
                    row[reader.GetName(i)] = reader[i];
                }
                data.Rows.Add(row);
            }
        }

        public bool IsConnected()
        {
            SqlConnection conn = GetConnection();
    
            bool tof = true;
            try
            {
                conn.Open();
            }
            catch (Exception e)
            {
                tof = false;
                throw e;
            }

            return tof;
        }

        SqlConnection GetConnection()
        {
            return new SqlConnection(ConfigHelper.DbConnectStr);
        }
    }
}
